import { IUser, IUserResponse, ICreateUserRequest, IUpdateUserRequest } from '../types';
import { UserRole } from '../consts/role';

// 用户数据模型
// 这里使用内存存储，实际项目中应该使用数据库

let users: IUser[] = [
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    password: 'admin123',
    role: UserRole.ADMIN,
    createdAt: new Date('2024-01-01'),
    updatedAt: new Date('2024-01-01')
  },
  {
    id: 2,
    username: 'user1',
    email: 'user1@example.com',
    password: 'user123',
    role: UserRole.USER,
    createdAt: new Date('2024-01-02'),
    updatedAt: new Date('2024-01-02')
  }
];

let nextId = 3;

class User {
  static findAll(): IUserResponse[] {
    return users.map(user => {
      const { password, ...userWithoutPassword } = user;
      return userWithoutPassword;
    });
  }

  static findById(id: number | string): IUserResponse | null {
    const user = users.find(u => u.id === parseInt(id.toString(), 10));
    if (user) {
      const { password, ...userWithoutPassword } = user;
      return userWithoutPassword;
    }
    return null;
  }

  static findByUsername(username: string): IUser | null {
    return users.find(u => u.username === username) || null;
  }

  static findByEmail(email: string): IUser | null {
    return users.find(u => u.email === email) || null;
  }

  static create(userData: ICreateUserRequest): IUserResponse {
    const newUser: IUser = {
      id: nextId++,
      username: userData.username,
      email: userData.email,
      password: userData.password, 
      role: userData.role || UserRole.USER,
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    users.push(newUser);
    
    const { password, ...userWithoutPassword } = newUser;
    return userWithoutPassword;
  }

  // 更新用户
  static update(id: number | string, userData: IUpdateUserRequest): IUserResponse | null {
    const userIndex = users.findIndex(u => u.id === parseInt(id.toString(), 10));
    if (userIndex === -1) {
      return null;
    }

    const updatedUser: IUser = {
      ...users[userIndex],
      ...userData,
      id: parseInt(id.toString(), 10), // 确保ID不被修改
      updatedAt: new Date()
    } as IUser;

    users[userIndex] = updatedUser;
    
    // 返回不包含密码的用户信息
    const { password, ...userWithoutPassword } = updatedUser;
    return userWithoutPassword;
  }

  // 删除用户
  static delete(id: number | string): boolean {
    const userIndex = users.findIndex(u => u.id === parseInt(id.toString(), 10));
    if (userIndex === -1) {
      return false;
    }

    users.splice(userIndex, 1);
    return true;
  }

  // 验证用户数据
  static validate(userData: Partial<ICreateUserRequest>, isUpdate = false): string[] {
    const errors: string[] = [];

    if (!isUpdate || userData.username !== undefined) {
      if (!userData.username || userData.username.trim().length < 3) {
        errors.push('用户名至少需要3个字符');
      }
    }

    if (!isUpdate || userData.email !== undefined) {
      if (!userData.email || !this.isValidEmail(userData.email)) {
        errors.push('请提供有效的邮箱地址');
      }
    }

    if (!isUpdate || userData.password !== undefined) {
      if (!userData.password || userData.password.length < 6) {
        errors.push('密码至少需要6个字符');
      }
    }

    return errors;
  }

  // 邮箱格式验证
  static isValidEmail(email: string): boolean {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }
}

export default User;
